import requests
import json
import os
from threading import Thread
from src.utils.redis_pool import redis_conn
from src.utils.config import config
from src.utils.dingding_message import dingding_messager


class DingdingB2bMessager:
    def __init__(self):
        self.message_url = config.get_config('dingdingb2b', 'robot')
        self.headers = {
            "Content-Type": "application/json"
        }

    def async(f):
        def wrapper(*args, **kwargs):
            thr = Thread(target=f, args=args, kwargs=kwargs)
            thr.start()

        return wrapper

    @async
    def send_message(self, message):
        server = os.environ.get('API_SERVER_INFO')
        env = 'test' if os.environ.get('environment') is None else os.environ.get('environment')
        msg = "## [{}价格]b2b-fundation-skulevel接口报警！\nskulevel详情："
        msg = msg.format(env)+message
        if server is not None:
            msg = msg + '  \nFrom Price Model server@{}'.format(server)
        # if os.environ.get('environment') == 'deploy':
        #     # product环境
        #     msg = msg + '[deploy]'
        # elif os.environ.get('environment') == 'fattest':
        #     # 测试环境在message前后加入"测试"字样
        #     msg = msg + '[fat]'
        # elif os.environ.get('environment') == 'uat':
        #     # 测试环境在message前后加入"测试"字样
        #     msg = msg + '[uat]'
        # else:
        #     msg = msg + '[test]'
        # hashMd5= hashForString("md5",msg)
        # state = redis_conn.get(hashMd5)
        # if state is None :
        #     redis_conn.set(hashMd5, 1, ex=60*1)
        # else:
        #     return

        data={"msgtype": "markdown", "markdown": {"title": "skulevel服务报警", "text": ""}}
        data['markdown']['text'] = msg
        requests.post(self.message_url, headers=self.headers,
                      data=json.dumps(data), timeout=5)


dingding_b2b_messager = DingdingB2bMessager()

if __name__=="__main__":
    dingding_b2b_messager.send_message('1618')
    dingding_messager.send_message('1618')
